<template>
  <div id="intfconfig">
    <Splitpanes style="height: 100%">
      <Pane :size="leftpane">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button
              type="text"
              status="primary"
              icon="vxe-icon-refresh"
              content="刷新"
              @click="handleSearch"
            ></vxe-button>
            <vxe-button
              type="text"
              status="success"
              icon="vxe-icon-square-plus"
              content="新建"
              @click="handleAdd"
            ></vxe-button>
            <vxe-button
              type="text"
              status="danger"
              icon="vxe-icon-delete"
              content="删除"
              @click="handleDelete"
            ></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="modulTable">
          <vxe-table
            ref="moduleTable"
            v-loading="loading"
            :loading="loading"
            :height="conHeight - 150 + 'px'"
            border
            :data="intfItemList"
            @current-change="moduleRowClick"
            :row-config="{ isCurrent: true, isHover: true }"
            :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }"
            @cell-dblclick="editRow"
            :edit-rules="formRule"
            resizable
            show-overflow
            keep-source
          >
            <vxe-column type="checkbox" width="26" align="center"></vxe-column>
            <vxe-column type="seq" title="序号" width="30" align="center"></vxe-column>
            <vxe-column
              field="code"
              title="编码"
              width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.code"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="name"
              title="名称"
              min-width="120px"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.name"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="intfId"
              title="接口"
              width="100"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #default="{ row }">
                <span>{{ formatIntf(row.intfId) }}</span>
              </template>
            </vxe-column>
            <vxe-column
              field="sn"
              title="顺序"
              width="50"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #edit="{ row, rowIndex, column }">
                <vxe-input
                  v-model="row.sn"
                  type="text"
                  @keydown.enter="enterEvent(row, rowIndex, column)"
                ></vxe-input>
              </template>
            </vxe-column>
            <vxe-column
              field="state"
              title="状态"
              width="50"
              :edit-render="{ autofocus: '.vxe-input--inner' }"
            >
              <template #default="{ row }">
                <span>{{ formatCommon(stateDict, row.state) }}</span>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane :size="rightpane">
        <el-tabs model-value="set" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="设置" name="set">
            <CompIntfItemSettings :itemform="mainform" v-if="isitemconfigshow" />
          </el-tab-pane>
          <el-tab-pane label="调试" name="test">
            <CompIntfItemTest :itemform="mainform" v-if="isitemconfigshow" />
          </el-tab-pane>
          <el-tab-pane label="日志" name="log">
            <CompIntfItemLogs :itemform="mainform" v-if="isitemconfigshow" />
          </el-tab-pane>
        </el-tabs>
      </Pane>
    </Splitpanes>
    <!-- 新增/编辑接口  -->
    <el-dialog v-model="maindialogVisible" :title="mainform.id?'编辑方法':'新建方法'" width="60%" @open="openMainDialog">
      <el-form :model="mainform" label-width="100px">
        <Splitpanes style="height: 100%">
          <Pane size="50">
            <el-form-item label="ID">
              <el-input v-model="mainform.id" disabled />
            </el-form-item>
            <el-form-item label="接口">
              <el-select v-model="mainform.intfId" placeholder="请选择" disabled>
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in props.intfs"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="编码">
              <el-input v-model="mainform.code" />
            </el-form-item>
            <el-form-item label="名称">
              <el-input v-model="mainform.name" />
            </el-form-item>
            <el-form-item label="顺序">
              <el-input-number v-model="mainform.sn" :min="1" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="mainform.state" placeholder="请选择">
                <el-option label="未启用" :value="0" />
                <el-option label="启用" :value="1" />
              </el-select>
            </el-form-item>
          </Pane>
          <Pane size="50">
            <el-form-item label="执行类型">
              <el-radio-group v-model="mainform.type">
                <el-radio :label="'select'">表对表</el-radio>
                <el-radio :label="'call'">过程对表</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="外源表名">
              <el-input v-model="mainform.source" />
            </el-form-item>
            <el-form-item label="标准表名">
              <el-select v-model="mainform.standard" filterable placeholder="请选择" @change="changeStandard">
                <el-option
                  v-for="item in standardTableDict"
                  :key="item.id"
                  :label="item.name + ' ' + item.code"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="校准模板">
              <el-select v-model="mainform.template" filterable placeholder="请选择">
                <el-option
                  v-for="item in templateDict"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </Pane>
        </Splitpanes>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="maindialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRow">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ElMessage } from 'element-plus';
// import { fa } from 'element-plus/es/locale';
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
// import saveAs from 'file-saver';
import { defineProps } from 'vue';
import CompIntfItemSettings from './CompIntfItemSettings.vue'; //接口配置
import CompIntfItemTest from './CompIntfItemTest.vue'; //接口配置
import CompIntfItemLogs from './CompIntfItemLogs.vue'; //接口配置
let props = defineProps<{
  intfs: any[];
  intfId: string;
}>();
let store = AppStore();
let { proxy }: any = getCurrentInstance();
let modulePoitPre = reactive([]);
const stateDict = ref([
  { label: '未启用', value: 0 },
  { label: '启用', value: 1 }
]);
const standardTableDict = reactive([]);
const templateDict = reactive([]);
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.value == value) {
      return item.label;
    }
  }
}
function formatIntf(value) {
  for (const item of props.intfs) {
    if (item.id == value) {
      return item.name;
    }
  }
}
// 当前屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
let leftpane = ref('100');
let rightpane = ref('0');
//关键字
let keywords = ref('');
let loading = ref(false);
// 接口表格数据
let intfItemList = reactive([]);
let intfMainListAll = reactive([]);
let maindialogVisible = ref(false);
let mainform = reactive({
  id: '',
  code: '', //编码
  name: '', //名称
  intfId: '', //所属模块
  type: '', //类型
  state: 0, //状态
  sn: intfItemList.length + 1, //排序号
  //数据库
  source: '', //外源表
  standard: '', //标准表
  template: '', //校准模板
  settings: '', //配置细项
});

onMounted(() => {
  handleSearch();
  getStandardTableDict();
});

function getStandardTableDict() {
  standardTableDict.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDict/findDictListByType';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { code: 'INTF01' }
    })
    .then((res: any) => {
      standardTableDict.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}
function changeStandard(val) {
  mainform.template = '';
  findDictAndDetailList(val);
}
function openMainDialog() {
  if (!mainform.standard) return;
  findDictAndDetailList(mainform.standard);
}
function findDictAndDetailList(val) {
  templateDict.length = 0;
  const url = '/api/sys/basDict/findDictAndDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: val } })
    .then((res: any) => {
      const detailListTemp = res.data.detailList.sort((a, b) => a.sx - b.sx);
      for (const detail of detailListTemp) {
        if (detail.type == '模板') {
          templateDict.push({
            id: detail.id,
            code: detail.code,
            name: detail.name,
          })
        }
      }
    });
}
// 点击刷新
function handleSearch() {
  loading.value = true;
  isitemconfigshow.value = false;
  leftpane.value = '100';
  rightpane.value = '0';
  let intfParam = reactive({
    intfId: props.intfId
  });
  intfItemList.length = 0; //放入数据前清空数组
  proxy.$http.post('/api/sys/getIntfItemList', intfParam).then((res: any) => {
    if (res.status.code === 1) {
      loading.value = false;
      intfItemList.push(...res.data.sysIntfItemList);
      // if (moduleList.length > 0) {
      //   handleClickModule(moduleList[0], null, null);
      // }
    } else {
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}
//新建
async function handleAdd() {
  clearmainform();
  maindialogVisible.value = true;
  // intfItemList.push(record);
}
async function saveRow() {
  if (mainform.id) {
    proxy.$http
      .post('/api/sys/editIntfItem', mainform)
      .then((res: any) => {
        if (res.status.code === 1) {
          handleSearch();
          maindialogVisible.value = false;
          VXETable.modal.message({ content: '修改成功', status: 'success' });
        }
      })
      .catch((err: any) => {
        VXETable.modal.message({ content: '修改成功', status: 'error' });
      });
  } else {
    proxy.$http
      .post('/api/sys/addIntfItem', mainform)
      .then((res: any) => {
        if (res.status.code === 1) {
          handleSearch();
          maindialogVisible.value = false;
          VXETable.modal.message({ content: '创建成功', status: 'success' });
        }
      })
      .catch((err: any) => {
        VXETable.modal.message({ content: '创建异常', status: 'error' });
      });
  }
}
async function editRow({ row }) {
  clearmainform();
  setvalue(mainform, row);
  maindialogVisible.value = true;
}
function setvalue(form, row) {
  form.id = row.id;
  (form.code = row.code), //编码
    (form.name = row.name), //名称
    (form.intfId = row.intfId), //所属模块
    (form.type = row.type), //类型
    (form.state = row.state), //状态 禁用/调试/启用
    (form.sn = row.sn), //排序号
    //数据库
    (form.source = row.source), //数据库地址
    (form.standard = row.standard); //数据库名称
  form.template = row.template; //校准模板
  form.settings = row.settings; //配置细项
}
function clearmainform() {
  mainform.id = '';
  (mainform.code = ''), //编码
    (mainform.name = ''), //名称
    (mainform.intfId = props.intfId), //所属模块
    (mainform.type = 'select'), //类型
    (mainform.state = 0), //状态 禁用/调试/启用
    (mainform.sn = intfItemList.length + 1), //排序号
    //数据库
    (mainform.source = ''), //外源表
    (mainform.standard = ''); //标准表
  mainform.template = ''; //校准模板
  mainform.settings = ''; //配置细项
}
// 点击修改保存
async function saveList() {
  // 获取表格实例
  let $Xtable = proxy.$refs.moduleTable;

  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    // const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
    //   return m.id === '';
    // });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = intfItemList.filter(e => {
      return e.id === '';
    });


    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach(e => {
      let moduleAddParam = e;
    });

    // 新增
    InsertRecords.forEach(e => {
      const moduleAddParam = e;
      moduleAddParam.id = '1';
    });
    // localStorage.setItem('activeIndex', JSON.parse(JSON.stringify(this.intfItemList)));
    localStorage.setItem('intfItemList', JSON.stringify(intfItemList));
    VXETable.modal.message({ content: '操作成功', status: 'success' });
    setTimeout(() => {
      handleSearch();
    }, 500);
  } else {
    return;
  }
}
// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.moduleTable;
  let selectRows = $Xtable.getCheckboxRecords();
  if (selectRows.length > 1) {
    VxeMessage('只能删除一条数据', VxeNotifyType.warning);
    return;
  }
  if (selectRows <= 0) {
    VXETable.modal.message({ content: `请勾选要删除的数据`, status: 'warning' });
    return;
  } else {
    proxy
      .$confirm('确定删除此接口子项？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        proxy.$http
          .delete('/api/sys/deleteIntfItem/' + selectRows[0].id)
          .then((res: any) => {
            if (res.data == null) {
              VXETable.modal.message({ content: res.status.msg, status: 'warning' });
              VxeMessage('删除接口子项失败', VxeNotifyType.error);
            } else {
              VxeMessage('删除接口子项成功', VxeNotifyType.success);
              handleSearch();
            }
          })
          .catch((err: any) => {
            VxeMessage('删除异常', VxeNotifyType.error);
          });
      });
  }
}
let isitemconfigshow = ref(false);
// 点击行
function moduleRowClick({ row, rowIndex }) {
  if (isitemconfigshow.value) {
    isitemconfigshow.value = false;
  }
  clearmainform();
  setvalue(mainform, row);
  leftpane.value = '30';
  rightpane.value = '70';
  setTimeout(() => {
    isitemconfigshow.value = true;
  }, 500);
}
</script>
<style lang="scss" scoped>
#intfconfig {
  .el-form-item {
    margin-right: 10px;
  }
  .el-tabs {
    margin-left: 10px;
  }
  .el-select {
    width: 100%;
  }
  .el-input-number {
    width: 100%;
  }
}
</style>
